package com.usian.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.common.fastdfs.FastDFSClient;
import com.usian.mapper.WmMaterialMapper;
import com.usian.mapper.WmNewsMaterialMapper;
import com.usian.model.common.dtos.PageResponseResult;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.dtos.WmMaterialDto;
import com.usian.model.media.pojos.WmMaterial;
import com.usian.model.media.pojos.WmNewsMaterial;
import com.usian.model.media.pojos.WmUser;
import com.usian.service.WmMaterialService;
import com.usian.utils.threadlocal.WmThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {


    @Autowired
    private FastDFSClient fastDFSClient;
    @Value("${fileServerUrl}")
    private String fileServerUrl;

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Override
    public ResponseResult uploadPic(MultipartFile file) {



        try {
            if(file==null){
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
            }
            String filePath = fastDFSClient.uploadFile(file);

            System.out.println("上传图片得到的地址："+filePath);


            //保存素材表
            WmMaterial wmMaterial =new WmMaterial();
            wmMaterial.setUrl(filePath);
            //获取当前登录用户 存在本地线程中
            WmUser wmUser = WmThreadLocalUtils.getUser();
            if(wmUser!=null){
                wmMaterial.setUserId(wmUser.getId());
            }
            wmMaterial.setIsCollection((short)0);
            wmMaterial.setType((short)0);
            wmMaterial.setCreatedTime(new Date());
            this.save(wmMaterial);


            wmMaterial.setUrl(fileServerUrl+filePath);
            return ResponseResult.okResult(wmMaterial); //目的为了图片回显

        } catch (IOException e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }
    }

    @Override
    public ResponseResult findList(WmMaterialDto dto) {

        //1:校验参数
        if(dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();

        Page page =new Page(dto.getPage(),dto.getSize());

        LambdaQueryWrapper<WmMaterial> lambdaQueryWrapper =new LambdaQueryWrapper<>();
        //条件  查询自己素材库   收藏     入库时间倒序排序
        WmUser wmUser = WmThreadLocalUtils.getUser();
        if(wmUser!=null){
            lambdaQueryWrapper.eq(WmMaterial::getUserId,wmUser.getId());
        }
        if(dto.getIsCollection()!=null && dto.getIsCollection()==1){
            lambdaQueryWrapper.eq(WmMaterial::getIsCollection,dto.getIsCollection());
        }
        lambdaQueryWrapper.orderByDesc(WmMaterial::getCreatedTime);

        IPage result =this.page(page,lambdaQueryWrapper);

        ResponseResult responseResult =new PageResponseResult(dto.getPage(),dto.getSize(),(int)result.getTotal());

        //把查询集合中的图片url进行拼接，目的图片回显
        List<WmMaterial> resultRecords = result.getRecords();
        resultRecords = resultRecords.stream().map(a->{
            a.setUrl(fileServerUrl + a.getUrl());
            return a;
        }).collect(Collectors.toList());

        //重新封装
        responseResult.setData(resultRecords);

        return responseResult;
    }

    @Override
    public ResponseResult delPic(Integer id) {

        if(id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //1:判断图片是否被引用 ，wm_news_material 有没有数据
        LambdaQueryWrapper<WmNewsMaterial> lambdaQueryWrapper =new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(WmNewsMaterial::getMaterialId,id);
        Integer count = wmNewsMaterialMapper.selectCount(lambdaQueryWrapper);

        if(count>0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"素材有引用不能删除");
        }

        this.removeById(id);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult updateStatus(Integer id, Short status) {

        if(id==null || status==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        WmUser wmUser = WmThreadLocalUtils.getUser();
        Integer userId=null;
        if(wmUser!=null){
            userId =wmUser.getId();
        }
        this.update(Wrappers.<WmMaterial>lambdaUpdate().set(WmMaterial::getIsCollection,status)
        .eq(WmMaterial::getId,id).eq(WmMaterial::getUserId,userId));

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
